import 'package:common_utils/common_utils.dart';
import 'package:dss_base/dss_base.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:dss_base/ext/string_ext.dart';
import 'package:flutter/widgets.dart';

class ImageX extends StatelessWidget {
  const ImageX({
    super.key,
    this.urlOrPath,
    this.placePath = 'dss_base/ic_img_loading.png',
    this.errorPath = 'dss_base/ic_img_error.png',
    this.fit = BoxFit.contain,
    this.width,
    this.height,
  });

  final String? urlOrPath;
  final String? placePath;
  final String? errorPath;
  final BoxFit fit;
  final double? width;
  final double? height;

  @override
  Widget build(BuildContext context) {
    if (TextUtil.isEmpty(urlOrPath)) {
      return errorPath != null ? _buildAssetImage(errorPath!, fit) : Gaps.empty;
    }
    if (urlOrPath!.startsWith("http")) {
      final PlaceholderWidgetBuilder? placeWidget = placePath != null
          ? (_, __) => _buildAssetImage(placePath!, fit)
          : null;
      final LoadingErrorWidgetBuilder? errorWidget = errorPath != null
          ? (_, __, dynamic error) => _buildAssetImage(errorPath!, fit)
          : null;
      return _buildNetworkImage(urlOrPath!, fit, placeWidget, errorWidget);
    } else {
      return _buildAssetImage(urlOrPath!, fit);
    }
  }

  /// 加载网络图片
  Widget _buildNetworkImage(
    String url,
    BoxFit fit,
    PlaceholderWidgetBuilder? placeBuilder,
    LoadingErrorWidgetBuilder? errorBuilder,
  ) {
    return CachedNetworkImage(
      imageUrl: url,
      placeholder: placeBuilder,
      errorWidget: errorBuilder,
      fit: fit,
      width: width,
      height: height,
    );
  }

  /// 加载本地图片
  Widget _buildAssetImage(String path, BoxFit fit) {
    String? package = path.startsWith('dss_base/') ? 'dss_base' : null;
    return Image.asset(
      path.toAssetsImagesPath(),
      fit: fit,
      package: package,
      width: width,
      height: height,
    );
  }
}
